<template>
    <div class="water-dict">

        <common-table>
            <template #header>
                <div class="flex-x-start">
                    <el-input style="width: 250px;" v-model="state.queryParams.keyword" placeholder="请输入字典"></el-input>
                    <el-button style="margin-left: 10px;" type="primary" @click="onSearch">查询</el-button>
                    <el-button @click="handleDispose('add')" style="margin-left: 10px;" type="primary">
                        添加字典
                    </el-button>
                </div>
            </template>

            <el-table align="center" height="100%" border :data="state.dictList">
                <el-table-column align="center" min-width="100" prop="value" label="联系人"></el-table-column>
                <el-table-column align="center" min-width="130" prop="phone" label="手机号"></el-table-column>
                <el-table-column align="center" min-width="100" prop="stock" label="水票数量"></el-table-column>
                <el-table-column align="center" min-width="100" prop="price" label="单价"></el-table-column>
                <el-table-column align="center" min-width="100" prop="desc" label="描述"></el-table-column>
                <el-table-column align="center" min-width="170" prop="created_at" label="创建时间">
                    <template #default="{ row }">
                        {{ formatDateTime(row.created_at) }}
                    </template>
                </el-table-column>
                <el-table-column align="center" min-width="170" prop="updated_at" label="更新时间">
                    <template #default="{ row }">
                        {{ formatDateTime(row.updated_at) }}
                    </template>
                </el-table-column>

                <!-- 操作 -->
                <el-table-column fixed="right" align="center" width="220" label="操作">
                    <template #default="{ row }">
                        <div class="flex justify-center">
                            <el-button type="success" size="small"
                                @click="handleDispose('recharge', row)">添加库存</el-button>
                            <el-button type="primary" size="small" @click="handleDispose('edit', row)">编辑</el-button>
                            <el-button type="warning" size="small" @click="handleDispose('delete', row)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <el-pagination v-model:current-page="state.queryParams.page" v-model:page-size="state.queryParams.limit"
                    @current-change="onSearch" :page-sizes="[10, 20, 30, 40]"
                    layout="total, sizes, prev, pager, next, jumper" :total="state.total">
                </el-pagination>
            </template>
        </common-table>
        <el-dialog @close="handleClose" v-model="dialogVisible" width="600px" :title="state.dialogTitle">
            <el-form v-if="state.dialogType !== 'recharge'" :model="state.form" :rules="formRules" ref="formRef"
                label-width="auto">
                <el-form-item label="手机号" prop="phone">
                    <el-input :disabled="state.dialogType === 'edit'" v-model="state.form.phone"
                        placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="联系人" prop="value">
                    <el-input v-model="state.form.value" placeholder="请输入联系人"></el-input>
                </el-form-item>
                <el-form-item label="库存" prop="stock">
                    <el-input-number v-model="state.form.stock" placeholder="请输入库存"></el-input-number>
                </el-form-item>
                <el-form-item label="水单价" prop="price">
                    <el-input v-model="state.form.price" placeholder="请输入水单价"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="state.form.desc" placeholder="请输入描述"></el-input>
                </el-form-item>
            </el-form>
            <div v-if="state.dialogType === 'recharge'">
                <el-form :model="state.rechargeForm" :rules="state.rechargeRules" ref="rechargeFormRef"
                    label-width="auto">
                    <el-form-item label="添加库存" prop="amount">
                        <el-input type="number" v-model="state.rechargeForm.amount" placeholder="请输入添加库存"></el-input>
                    </el-form-item>
                </el-form>
            </div>

            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang='ts'>
import CommonTable from '@/components/common-table.vue'
import { computed, reactive, ref } from 'vue'
import { formatDateTime } from '@/utils/formart'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { WaterApi } from '@/api/water'

const queryInit = {
    page: 1,
    limit: 10,
    keyword: ''
}

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)

const state = reactive<any>({
    queryParams: Object.assign({}, queryInit),
    dictList: [],
    total: 0,
    currentRow: {},
    dialogType: 'add',
    dialogTitle: '添加字典',
    rules: {
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        value: [{ required: true, message: '请输入值', trigger: 'blur' }]
    },
    rechargeRules: {
        amount: [{ required: true, message: '请输入添加库存', trigger: 'blur' }]
    },

    form: {},
    rechargeForm: {
        dictId: '',
        amount: 0
    }
})

const formRules = computed(() => {
    return state.dialogType === 'add' ? state.rules : []
})

const onSearch = () => {
    WaterApi.getDictList(state.queryParams).then(res => {
        state.dictList = res.data.data
        state.total = res.data.total
    })
}

const handleClose = () => {
    state.form = {}
    formRef.value?.resetFields()

}

const handleDispose = (type: string, row?: any) => {
    state.currentRow = row || {}
    if (type === 'edit') {
        state.form = { ...state.currentRow }
    }
    switch (type) {
        case 'add':
        case 'edit':
            dialogVisible.value = true
            state.dialogType = type
            state.dialogTitle = state.dialogType === 'add' ? '添加字典' : '编辑字典'
            break;
        case 'recharge':
            state.rechargeForm.dictId = state.currentRow.id
            state.dialogType = type
            state.dialogTitle = '添加库存'
            dialogVisible.value = true
            break;
        case 'delete':
            ElMessageBox.confirm('确定删除此字典吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                WaterApi.deleteDict({
                    dictId: state.currentRow.id
                }).then(res => {
                    if (res.code === 200) {
                        ElMessage.success('删除成功')
                        onSearch()
                    }
                })
            })
            break;
    }
}

const onSubmit = () => {
    if (state.dialogType === 'recharge') {
        state.rechargeForm.amount = parseFloat(state.rechargeForm.amount)
        WaterApi.recharge(state.rechargeForm).then(res => {
            if (res.code === 200) {
                ElMessage.success('添加库存成功')
                onSearch()
                dialogVisible.value = false
            }
        })
        return
    }
    formRef.value?.validate().then(() => {
        if (state.dialogType === 'add') {
            console.log(state.form);
            state.form.price = Number(state.form.price)
            WaterApi.createDict(state.form).then(res => {
                if (res.code === 200) {
                    ElMessage.success('添加成功')
                    onSearch()
                    dialogVisible.value = false
                }
            })
        } else {
            state.form.price = Number(state.form.price)
            state.form.dictId = state.currentRow.id
            WaterApi.createDict(state.form).then(res => {
                if (res.code === 200) {
                    ElMessage.success('更新成功')
                    onSearch()
                    dialogVisible.value = false
                }
            })
        }
    })
}


const init = () => {
    onSearch()
}

init()


</script>
<style scoped lang='scss'>
.water-dict {
    height: 100%;
}
</style>
